﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ProjectManagement.Domain.AutoMappings;
using ProjectManagement.Domain.Entities;
using ProjectManagement.Web.Common;
using ProjectManagement.Domain.Services;
using System.Web.Security;
using ProjectManagement.Web.Infrastructure;

namespace ProjectManagement.Web.Controllers
{
	public class HomeController : Controller
	{
		//登陆界面
		public ActionResult Index()
		{
			return View();
		}

		//登陆验证
		public ActionResult Login(FormCollection form)
		{
			UserService _userService = new UserService();
			string username = form["username"].ToString();
			string password = form["password"].ToString();
			string vrefyCode = form["verifycode"].ToString();
			if (vrefyCode != Session["SN"].ToString())
			{
				TempData["Message"] = "验证码不正确！";
				return RedirectToAction("Index");
			}
			var user = _userService.ExitUser(username,password);
			if (user.Count()>=1)
			{
				var currentUser = user.FirstOrDefault();
				if (currentUser.Allowed)
				{
					currentUser.IP = Request.UserHostAddress.ToString();
					currentUser.LastLogonTime = DateTime.Now;
					_userService.Update(currentUser);
					//保存用户名
					FormsAuthentication.SetAuthCookie(username, false);
					//保存FormsAuthenticationTicket
					FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(
						1,
						currentUser.UserName, //user id
						DateTime.Now,
						DateTime.Now.AddMinutes(20),  // expiry
						false,  //do not remember
						currentUser.ID.ToString(),
						"/");
					HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(authTicket));
					Response.ContentType = "UTF-8";
					Response.Cookies.Add(cookie);

					return RedirectToAction("Manage");
				}
				else
				{
					TempData["Message"] = "账号已禁用！";
					return RedirectToAction("Index");
				}
			}
			else
			{
				TempData["Message"] = "用户名或密码不正确！";
				return RedirectToAction("Index");
			}
		}
		//后台管理
		[Authorize]
		public ActionResult Manage()
		{
			return View();
		}
		//后台顶部
		[Authorize]
		public ActionResult Top()
		{
			TempData["Name"] = HttpContext.User.Identity.Name;
			return View();
		}
		//后台左侧
		[Authorize]
		public ActionResult Left()
		{
			return View();
		}
		//后台右侧
		[Authorize]
		public ActionResult Right()
		{
			return View();
		}
		//生成验证码及图片
		public ActionResult GetValaidCode()
		{
			string str = Commom.CreateValidateString(4);
			Session["SN"] = str;
			byte[] bt = Commom.CreateValidateCode(str);
			return File(bt, "image/jpeg");
		}
		//退出登录
		public ActionResult LogOut()
		{
			FormsAuthentication.SignOut();
			Session.Abandon();
			return View("Index");
		}
	}
}

